﻿using System;
using System.IO;
using System.Collections;

using OL = Microsoft.Office.Interop.Outlook;

using Domino;
using System.Runtime.InteropServices;

using ConvergensSettings;
using ConvergensConnector;

using Redemption;
using System.Diagnostics;
using System.Collections.Generic;
using System.Data;
using System.Linq;


namespace ConvergensDominoConnector
{
    public class DominoConnector
    {
        private NotesDatabase CDCODB;
        private NotesDocument newDoc;
        private NotesAgent cdcoAgent;
        private string noteid;

        private NotesDatabase profildb;
        private NotesDatabase emneorddb;
        private NotesDatabase mininabdb;

        private ArrayList eMailAttachments = new ArrayList();

        private const string LESS_THAN = "<";
        private const string GREATER_THAN = ">";
        private const string SPACE = " ";

        //private NotesMIMEEntity notesMIMEEntity = null;
        //private NotesStream notesStream = null;

        //Singleton Pattern
        private static DominoConnector SINGLETON = null;

        public static DominoConnector Default
        {
            get
            {
                if (DominoConnector.SINGLETON == null)
                {
                    try
                    {
                        DominoConnector.SINGLETON = new DominoConnector();
                    }
                    catch (COMException ex)
                    {
                        if (ex.ErrorCode == -2147467259)
                        {
                            DominoConnector.SINGLETON = null;
                        }
                        
                        throw ex;

                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Notes initialiseringsfejl.\n\nSystem besked:\n" + ex.Message + "\n\n" + ex.StackTrace);
                    }
                }

                return DominoConnector.SINGLETON;
            }
        }

        private NotesSession notesSession = new NotesSessionClass();

        private DominoConnector()
        {
            try
            {
                this.notesSession.Initialize(string.Empty);
            }
            catch (COMException cx)
            {
                Marshal.ReleaseComObject(this.notesSession);

                if (cx.ErrorCode == -2147217504)
                {

                    throw new COMException("CDCOSDH COMException:\n" + cx.Message + "\n\n"+ cx.StackTrace);
                }
                else
                {
                    throw new COMException("CDCOSDH COMException:\n" + cx.Message + "\n\n" + cx.StackTrace);
               }
            }
        }

        public NotesDatabase GetMailDatabase(string serverName)
        {
            try
            {
                NotesDatabase notesDatabase;
                NotesDbDirectory notesDbDirectory;

                notesDbDirectory = this.notesSession.GetDbDirectory(serverName);


                try
                {
                    notesDatabase = notesDbDirectory.OpenMailDatabase();
                    
                }
                catch (Exception ex)
                {

                    throw new Exception("Maildatabasen kunne ikke åbnes.\nBrugernavn:\n" + this.notesSession.UserName + "\n\nSystem besked:\n" + ex.Message);
                }


                return notesDatabase;
            }
            catch (Exception)
            {
                throw;
            }
        }

        public NotesSession NotesSession
        {
            get
            {
                return this.notesSession;
            }
        }

        public string CommonName
        {
            get
            {
                return this.notesSession.CommonUserName;
            }
        }

        #region Stuff for converting a mail item to a domino document

        public void journalizeMailItem(OL.MailItem mailItem, JournalizeSingleValues jsv, bool insertRef, bool outlookSend)
        {
            string messageHeadersEmailAddress = string.Empty;
            bool isSaved = false;
            string tempString = string.Empty;
            bool openCase = jsv.JnalSgl_CbOpenCase;
            OL.Recipients recipients = mailItem.Recipients;

            #region Insert Ref

            if (insertRef)
            {
                mailItem.Body = "Reference: " + jsv.JnalSgl_TbCaseNum + Environment.NewLine + Environment.NewLine + mailItem.Body;
                mailItem.Save();
            }

            #endregion

            #region create new docoument
            // Create a Document
            this.CDCODB = this.GetMailDatabase(CDCOFileSettings.Instance.MailServerName);
            this.newDoc = this.CDCODB.CreateDocument();

            #region AppendItemValues "Form" 
            this.newDoc.AppendItemValue("Form", CDCOFileSettings.Instance.Form);
            #endregion

            #region Get SendTo field from Outlook and copy to document
            if (!string.IsNullOrEmpty(mailItem.To))
            {
                NotesItem tempItem = this.newDoc.ReplaceItemValue(CDCOFileSettings.Instance.To, "");

                if (recipients.Count > 0)
                {
                    for (int i = 1; i <= recipients.Count; i++)
                    {
                        OL.Recipient recipient = recipients[i];
                        if (recipient.Type == 1)
                        {
                            OL.AddressEntry addressEntry = recipients[i].AddressEntry;
                            if (!addressEntry.Address.Contains("@"))
                            {
                                tempItem.AppendToTextList(addressEntry.Name + SPACE + LESS_THAN + this.GetSMTPAddress(addressEntry.Address) + GREATER_THAN);
                            }
                            else
                            {
                                tempItem.AppendToTextList(addressEntry.Name + SPACE + LESS_THAN + addressEntry.Address + GREATER_THAN);
                            }
                        }

                    }
                }

                tempItem.CopyItemToDocument(this.newDoc, CDCOFileSettings.Instance.To);
                tempItem = null;
                tempString = string.Empty;
            }
            #endregion

            #region Get CopyTo field from Outlook and copy to document
            if (!string.IsNullOrEmpty(mailItem.CC))
            {
                NotesItem tempItem = this.newDoc.ReplaceItemValue(CDCOFileSettings.Instance.Cc, "");

                if (recipients.Count > 0)
                {
                    for (int i = 1; i <= recipients.Count; i++)
                    {
                        OL.Recipient recipient = recipients[i];
                        if (recipient.Type == 2)
                        {
                            OL.AddressEntry addressEntry = recipients[i].AddressEntry;
                            if (!addressEntry.Address.Contains("@"))
                            {
                                tempItem.AppendToTextList(addressEntry.Name + SPACE + LESS_THAN + this.GetSMTPAddress(addressEntry.Address) + GREATER_THAN);
                            }
                            else
                            {
                                tempItem.AppendToTextList(addressEntry.Name + SPACE + LESS_THAN + addressEntry.Address + GREATER_THAN);
                            }
                        }

                    }
                }

                tempItem.CopyItemToDocument(this.newDoc, CDCOFileSettings.Instance.Cc);
                tempItem = null;
                tempString = string.Empty;
            }
            #endregion

            #region Get BlindCopyTo field from Outlook and copy to document
            if (!string.IsNullOrEmpty(mailItem.BCC))
            {
                NotesItem tempItem = this.newDoc.ReplaceItemValue(CDCOFileSettings.Instance.Bcc, "");

                if (recipients.Count > 0)
                {
                    for (int i = 1; i <= recipients.Count; i++)
                    {
                        OL.Recipient recipient = recipients[i];
                        if (recipient.Type == 3)
                        {
                            OL.AddressEntry addressEntry = recipients[i].AddressEntry;
                            if (!addressEntry.Address.Contains("@"))
                            {
                                tempItem.AppendToTextList(addressEntry.Name + SPACE + LESS_THAN + this.GetSMTPAddress(addressEntry.Address) + GREATER_THAN);
                            }
                            else
                            {
                                tempItem.AppendToTextList(addressEntry.Name + SPACE + LESS_THAN + addressEntry.Address + GREATER_THAN);
                            }
                        }

                    }
                }

                tempItem.CopyItemToDocument(this.newDoc, CDCOFileSettings.Instance.Bcc);
                tempItem = null;
                tempString = string.Empty;
            }
            #endregion

            #region AppendItemValues "From" "Subject" "Date" "DocID" "Type" "Type2" "CaseTitle" "ToArchive" "PasteOK" "JournalSubject" "jViewIcon"

            switch (mailItem.SenderEmailType)
            {
                //case "SMTP":
                //    messageHeadersEmailAddress = this.removeCommaAndReverse(mailItem.SenderName) + SPACE + LESS_THAN + mailItem.SenderEmailAddress + GREATER_THAN;
                //    break;
                case "EX":
                    this.newDoc.AppendItemValue(CDCOFileSettings.Instance.ResolvedSenderEmailAdress, this.GetSTMPFromEXAddress(mailItem));
                    //fra outlook adress book project
                    //messageHeadersEmailAddress = this.getSTMPFromEXAddress(mailItem);
                    //messageHeadersEmailAddress = mailItem.SenderName + SPACE + LESS_THAN + messageHeadersEmailAddress + GREATER_THAN;
                    //messageHeadersEmailAddress = messageHeadersEmailAddress.Trim();
                    break;
                //case "NOTES":
                //    messageHeadersEmailAddress = mailItem.SenderEmailAddress;
                //    break;
                default:
                    break;
            }

            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.BodyFormat, mailItem.BodyFormat);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.EntryID, mailItem.EntryID);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.ConversationID, mailItem.ConversationID);

            OL.Account account = mailItem.SendUsingAccount;

            if (outlookSend)
            {
                this.newDoc.AppendItemValue(CDCOFileSettings.Instance.SentOn, mailItem.ReceivedTime);
            }
            else
            {
                this.newDoc.AppendItemValue(CDCOFileSettings.Instance.SentOn, mailItem.SentOn);
            }

            if (outlookSend)
            {
                this.newDoc.AppendItemValue(CDCOFileSettings.Instance.SenderName, account.UserName);
            }
            else
            {
                this.newDoc.AppendItemValue(CDCOFileSettings.Instance.SenderName, mailItem.SenderName);
            }

            if (outlookSend)
            {
                this.newDoc.AppendItemValue(CDCOFileSettings.Instance.SenderEmailAddress, account.SmtpAddress);
            }
            else
            {
                this.newDoc.AppendItemValue(CDCOFileSettings.Instance.SenderEmailAddress, mailItem.SenderEmailAddress);
            }
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.SentOnBehalfOfName, mailItem.SentOnBehalfOfName);

            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.ReceivedTime, mailItem.ReceivedTime);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.ReceivedByName, mailItem.ReceivedByName);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.ReceivedOnBehalfOfName, mailItem.ReceivedOnBehalfOfName);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.ReplyRecipientNames, mailItem.ReplyRecipientNames);

            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.Subject, mailItem.Subject);

            #endregion

            #region Create body rich text field
            NotesRichTextItem notesRichTextItem = this.newDoc.CreateRichTextItem(CDCOFileSettings.Instance.Body);
            OL.OlBodyFormat bodyFormat = mailItem.BodyFormat;
            switch (bodyFormat)
            {
                case OL.OlBodyFormat.olFormatHTML:
                    if (!string.IsNullOrEmpty(mailItem.Body))
                    {
                        //this.notesStream = DominoConnector.Default.NotesSession.CreateStream();
                        //DominoConnector.Default.NotesSession.ConvertMime = false; //Do not convert MIME to rich text 
                        //this.notesMIMEEntity = this.newDoc.CreateMIMEEntity("Body");
                        //string[] encodingInfo = this.createTempHTMLEncoding(mailItem);
                        //this.notesStream.Open(encodingInfo[0], "Windows-" + encodingInfo[1]);
                        //this.notesMIMEEntity.SetContentFromText(notesStream, "text/HTML;charset=" + encodingInfo[2], MIME_ENCODING.ENC_IDENTITY_8BIT);
                        //this.notesStream.Close();
                        //DominoConnector.Default.NotesSession.ConvertMime = true; //Restore conversion
                        //File.Delete(encodingInfo[0]);
                        //encodingInfo.Initialize();

                        notesRichTextItem.AppendText(mailItem.Body.Replace("\r\n\r\n", "\r\n"));
                    }

                    if (mailItem.Attachments.Count > 0)
                    {
                        int i = 1;
                        this.eMailAttachments.Clear();
                        foreach (OL.Attachment attachment in mailItem.Attachments)
                        {
                            if (this.eMailAttachments.Contains(attachment.FileName))
                            {
                                string newFileName = attachment.FileName;

                                if (newFileName.Contains("."))
                                {
                                    string underScor = "_";
                                    int lastDot = newFileName.LastIndexOf('.');
                                    newFileName = newFileName.Insert(lastDot, underScor + i.ToString());
                                    this.eMailAttachments.Add(newFileName);
                                    i++;
                                }
                                else
                                {
                                    newFileName = newFileName + "_" + i.ToString();
                                    this.eMailAttachments.Add(attachment.FileName);

                                }
                            }
                            else
                            {
                                this.eMailAttachments.Add(attachment.FileName);
                                i = 1;
                            }
                        }

                        i = 0;
                        foreach (string attachmentsName in this.eMailAttachments)
                        {
                            foreach (OL.Attachment attachment in mailItem.Attachments)
                            {
                                if (attachmentsName == attachment.FileName)
                                {
                                    try
                                    {
                                        File.SetAttributes(Path.GetTempPath() + "\\" + this.eMailAttachments[i].ToString(), FileAttributes.Normal);
                                        File.Delete(Path.GetTempPath() + "\\" + this.eMailAttachments[i].ToString());
                                    }
                                    catch (Exception)
                                    {
                                        //Suspress all Exceptions
                                    }

                                    attachment.SaveAsFile(Path.GetTempPath() + "\\" + attachment.FileName);
                                    File.Move(Path.GetTempPath() + "\\" + attachment.FileName, Path.GetTempPath() + "\\" + this.eMailAttachments[i].ToString());


                                    notesRichTextItem.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, null, Path.GetTempPath() + "\\" + this.eMailAttachments[i].ToString(), Path.GetTempPath() + "\\" + this.eMailAttachments[i].ToString());
                                    File.Delete(Path.GetTempPath() + "\\" + this.eMailAttachments[i].ToString());
                                    i++;
                                }
                            }
                        }

                    }
                    break;
                case OL.OlBodyFormat.olFormatPlain:
                    if (!string.IsNullOrEmpty(mailItem.Body))
                    {
                        notesRichTextItem.AppendText(mailItem.Body);
                    }
                    if (mailItem.Attachments.Count > 0)
                    {
                        int j = 1;
                        this.eMailAttachments.Clear();
                        foreach (OL.Attachment attachment in mailItem.Attachments)
                        {
                            if (this.eMailAttachments.Contains(attachment.FileName))
                            {
                                string newFileName = attachment.FileName;

                                if (newFileName.Contains("."))
                                {
                                    string underScor = "_";
                                    int lastDot = newFileName.LastIndexOf('.');
                                    newFileName = newFileName.Insert(lastDot, underScor + j.ToString());
                                    this.eMailAttachments.Add(newFileName);
                                    j++;
                                }
                                else
                                {
                                    newFileName = newFileName + "_" + j.ToString();
                                    this.eMailAttachments.Add(attachment.FileName);

                                }
                            }
                            else
                            {
                                this.eMailAttachments.Add(attachment.FileName);
                                j = 1;
                            }
                        }

                        j = 0;
                        foreach (string attachmentsName in this.eMailAttachments)
                        {
                            foreach (OL.Attachment attachment in mailItem.Attachments)
                            {
                                if (attachmentsName == attachment.FileName)
                                {
                                    try
                                    {
                                        File.SetAttributes(Path.GetTempPath() + "\\" + this.eMailAttachments[j].ToString(), FileAttributes.Normal);
                                        File.Delete(Path.GetTempPath() + "\\" + this.eMailAttachments[j].ToString());
                                    }
                                    catch (Exception)
                                    {
                                        //Suspress all Exceptions
                                    }

                                    attachment.SaveAsFile(Path.GetTempPath() + "\\" + attachment.FileName);
                                    File.Move(Path.GetTempPath() + "\\" + attachment.FileName, Path.GetTempPath() + "\\" + this.eMailAttachments[j].ToString());


                                    notesRichTextItem.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, null, Path.GetTempPath() + "\\" + this.eMailAttachments[j].ToString(), Path.GetTempPath() + "\\" + this.eMailAttachments[j].ToString());
                                    File.Delete(Path.GetTempPath() + "\\" + this.eMailAttachments[j].ToString());
                                    j++;
                                }
                            }
                        }

                    }
                    break;
                case OL.OlBodyFormat.olFormatRichText:
                    if (!string.IsNullOrEmpty(mailItem.Body))
                    {
                        notesRichTextItem.AppendText(mailItem.Body);
                    }
                    if (mailItem.Attachments.Count > 0)
                    {
                        int k = 1;
                        this.eMailAttachments.Clear();
                        foreach (OL.Attachment attachment in mailItem.Attachments)
                        {
                            if (this.eMailAttachments.Contains(attachment.FileName))
                            {
                                string newFileName = attachment.FileName;

                                if (newFileName.Contains("."))
                                {
                                    string underScor = "_";
                                    int lastDot = newFileName.LastIndexOf('.');
                                    newFileName = newFileName.Insert(lastDot, underScor + k.ToString());
                                    this.eMailAttachments.Add(newFileName);
                                    k++;
                                }
                                else
                                {
                                    newFileName = newFileName + "_" + k.ToString();
                                    this.eMailAttachments.Add(attachment.FileName);

                                }
                            }
                            else
                            {
                                this.eMailAttachments.Add(attachment.FileName);
                                k = 1;
                            }
                        }

                        k = 0;
                        foreach (string attachmentsName in this.eMailAttachments)
                        {
                            foreach (OL.Attachment attachment in mailItem.Attachments)
                            {
                                if (attachmentsName == attachment.FileName)
                                {
                                    try
                                    {
                                        File.SetAttributes(Path.GetTempPath() + "\\" + this.eMailAttachments[k].ToString(), FileAttributes.Normal);
                                        File.Delete(Path.GetTempPath() + "\\" + this.eMailAttachments[k].ToString());
                                    }
                                    catch (Exception)
                                    {
                                        //Suspress all Exceptions
                                    }

                                    attachment.SaveAsFile(Path.GetTempPath() + "\\" + attachment.FileName);
                                    File.Move(Path.GetTempPath() + "\\" + attachment.FileName, Path.GetTempPath() + "\\" + this.eMailAttachments[k].ToString());


                                    notesRichTextItem.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, null, Path.GetTempPath() + "\\" + this.eMailAttachments[k].ToString(), Path.GetTempPath() + "\\" + this.eMailAttachments[k].ToString());
                                    File.Delete(Path.GetTempPath() + "\\" + this.eMailAttachments[k].ToString());
                                    k++;
                                }
                            }
                        }

                    }
                    break;
                default:
                    this.AppendNotesRichTextItem(mailItem);
                    break;
            }
            #endregion

            #region Save email as EML & MSG
            try
            {
                switch (CDCOFileSettings.Instance.SaveAsType)
                {
                    case "1":
                        {
                            NotesRichTextItem saveAsTypeRichTextItem = this.newDoc.CreateRichTextItem(CDCOFileSettings.Instance.Eml);
                            SafeMailItem safeMailItem = new SafeMailItem();
                            safeMailItem.Item = mailItem;
                            safeMailItem.SaveAs(Path.GetTempPath() + "KopiAfEMail" + ".eml", Redemption.RedemptionSaveAsType.olRFC822);
                            saveAsTypeRichTextItem.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, null, Path.GetTempPath() + "\\" + "KopiAfEMail" + ".eml", Path.GetTempPath() + "\\" + "KopiAfEMail" + ".eml");
                            File.Delete(Path.GetTempPath() + "\\" + "KopiAfEMail" + ".eml");
                            break;
                        }
                    case "2":
                        {
                            NotesRichTextItem saveAsTypeRichTextItem = this.newDoc.CreateRichTextItem(CDCOFileSettings.Instance.Msg);
                            mailItem.SaveAs(Path.GetTempPath() + "KopiAfEMail" + ".msg", OL.OlSaveAsType.olMSGUnicode);
                            saveAsTypeRichTextItem.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, null, Path.GetTempPath() + "\\" + "KopiAfEMail" + ".msg", Path.GetTempPath() + "\\" + "KopiAfEMail" + ".msg");
                            File.Delete(Path.GetTempPath() + "\\" + "KopiAfEMail" + ".msg");
                            break;
                        }
                    case "3":
                        {
                            NotesRichTextItem saveAsTypeRichTextItemEml = this.newDoc.CreateRichTextItem(CDCOFileSettings.Instance.Eml);
                            SafeMailItem safeMailItem = new SafeMailItem();
                            safeMailItem.Item = mailItem;
                            safeMailItem.SaveAs(Path.GetTempPath() + "KopiAfEMail" + ".eml", Redemption.RedemptionSaveAsType.olRFC822);
                            saveAsTypeRichTextItemEml.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, null, Path.GetTempPath() + "\\" + "KopiAfEMail" + ".eml", Path.GetTempPath() + "\\" + "KopiAfEMail" + ".eml");
                            File.Delete(Path.GetTempPath() + "\\" + "KopiAfEMail" + ".eml");

                            NotesRichTextItem saveAsTypeRichTextItemMsg = this.newDoc.CreateRichTextItem(CDCOFileSettings.Instance.Msg);
                            mailItem.SaveAs(Path.GetTempPath() + "KopiAfEMail" + ".msg", OL.OlSaveAsType.olMSGUnicode);
                            saveAsTypeRichTextItemMsg.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, null, Path.GetTempPath() + "\\" + "KopiAfEMail" + ".msg", Path.GetTempPath() + "\\" + "KopiAfEMail" + ".msg");
                            File.Delete(Path.GetTempPath() + "\\" + "KopiAfEMail" + ".msg");
                            break;
                        }
                    default:
                        break;
                }

            }
            catch (Exception)
            {

                throw new ApplicationException("Mailen kunne ikke journaliseres!");
            }

            #endregion
          
            #region JournalizeSingle fields
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.JnalSgl_CbSDH, jsv.JnalSgl_CbSDH);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.JnalSgl_TbCaseNum, jsv.JnalSgl_TbCaseNum);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.JnalSgl_Lbtitle, jsv.JnalSgl_LbTitle);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.JnalSgl_RbMustReply, jsv.JnalSgl_RbMustReply);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.JnalSgl_TbSeqNum, jsv.JnalSgl_TbSeqNum);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.JnalSgl_CbRplyReq, jsv.JnalSgl_CbRlpyReq);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.JnalSgl_CbCaseOfr, jsv.JnalSgl_CbCaseOfr);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.JnalSgl_LbMailRightSelected, jsv.JnalSgl_LbMailRightSelected);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.JnalSgl_TbDocName, jsv.JnalSgl_TbDocName);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.JnalSgl_TbRemarks, jsv.JnalSgl_TbRemarks);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.JnalSgl_CbCaseParts, jsv.JnalSgl_CbCaseParts);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.JnalSgl_CbFreeCat, jsv.JnalSgl_CbFreeCat);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.JnalSgl_LbCaseArea, jsv.JnalSgl_LbCaseArea);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.JnalSgl_LbEdction, jsv.JnalSgl_LbEdction);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.JnalSgl_LbInstitution, jsv.JnalSgl_LbInstitution);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.JnalSgl_LbLeglAspcts, jsv.JnalSgl_LbLeglAspcts);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.JnalSgl_LbEcoAspcts, jsv.JnalSgl_LbEcoAspcts);
            #endregion

            #region Save document to Domino
            isSaved = this.newDoc.Save(true, false);
            if (!isSaved)
            {
                throw new ApplicationException("Mailen kunne ikke journaliseres!");
            }
            else 
            {
                //Process.Start(this.newDoc.NotesURL);

                //Run CDCO Control Agent 
                this.cdcoAgent = this.CDCODB.GetAgent("CDCOSDH.InitializeCheck");
                this.noteid = newDoc.NoteID;
                this.cdcoAgent.RunOnServer(this.noteid);
                //this.newDoc = null;
                //Marshal.ReleaseComObject(this.newDoc);
                this.newDoc= this.CDCODB.GetDocumentByID(this.noteid);
                NotesDocument tempDoc = this.CDCODB.GetDocumentByID(this.noteid);
                
                //Array res = (Array)tempDoc.GetFirstItem("CDCOSDH_Control");
                NotesItem notesItem= this.newDoc.GetFirstItem("CDCOSDH_Control");
                object subject = tempDoc.GetItemValue("CDCOSDH_Control");


                //string resultstr = res[0]
                if (openCase)
                {
                    try
                    {
                        Process.Start(this.newDoc.NotesURL);
                        //System.Windows.Forms.MessageBox.Show(resultstr);
                        //run URL
                        //if (resultstr.Contains("OK="))
                       // {
                       //     string[] url = resultstr.Split('=');
                       //     System.Windows.Forms.MessageBox.Show(url[0]);
                       //     System.Windows.Forms.MessageBox.Show(url[1]);
                       //     Process.Start(url[0]);
                       //     Process.Start(url[1]);
                       // }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Failed to run open document \"" + this.newDoc.UniversalID
                            + "\"\n\nwith URL=" + this.CDCODB.NotesURL, ex);
                    }
                }
                // Husk de andre report og meeting

                string existingCategories = mailItem.Categories;
                if (String.IsNullOrEmpty(existingCategories))
                {
                    mailItem.Categories = "Journaliseret";
                }
                else
                {
                    if (mailItem.Categories.Contains("Journaliseret") == false)
                    {
                        mailItem.Categories = existingCategories + ", Journaliseret";
                    }
                }
                mailItem.Save();

                //mailItem.Categories = "Journaliseret";
                //mailItem.Save();

                if (outlookSend)
                {
                    mailItem.Send();
                }
            }
            #endregion

            #endregion// MailItem
        }

        public void journalizeReportItem(OL.ReportItem reportItem)
        {
            Type t = Type.GetTypeFromProgID("Redemption.SafeMailItem");
            SafeMailItem safeMailItem = (SafeMailItem)Activator.CreateInstance(t);
            safeMailItem.Item = reportItem;

            bool isSaved = false;
            string tempString = string.Empty;

            // Create a Document
            this.CDCODB = this.GetMailDatabase(ConvergensSettings.CDCOFileSettings.Instance.SDHServerName);
            this.newDoc = this.CDCODB.CreateDocument();

            #region AppendItemValues "Form"
            this.newDoc.AppendItemValue("Form", ConvergensSettings.CDCOFileSettings.Instance.RptItm_Form);
            #endregion

            #region Get SendTo field from Outlook and copy to document
            if (!string.IsNullOrEmpty(safeMailItem.To))
            {
                NotesItem tempItem = this.newDoc.ReplaceItemValue(ConvergensSettings.CDCOFileSettings.Instance.RptItm_To, "");
                if (safeMailItem.Recipients.Count > 0)
                {
                    for (int i = 1; i <= safeMailItem.Recipients.Count; i++)
                    {
                        if (safeMailItem.Recipients[i].Type == 1)
                        {
                            Redemption.AddressEntry addressEntry = safeMailItem.Recipients[i].AddressEntry;
                            if (!addressEntry.Address.Contains("@"))
                            {
                                tempItem.AppendToTextList(addressEntry.Name + SPACE + LESS_THAN + this.GetSMTPAddress(addressEntry.Address) + GREATER_THAN);
                            }
                            else
                            {
                                tempItem.AppendToTextList(addressEntry.Name + SPACE + LESS_THAN + addressEntry.Address + GREATER_THAN);
                            }
                        }

                    }
                }

                tempItem.CopyItemToDocument(this.newDoc, ConvergensSettings.CDCOFileSettings.Instance.RptItm_To);
                tempItem = null;
                tempString = string.Empty;
            }

            #endregion

            #region AppendItemValues "From" "Subject" "Date" 
            
            if (!safeMailItem.SenderEmailAddress.Contains("@"))
	        {
                this.newDoc.AppendItemValue(CDCOFileSettings.Instance.RptItm_ResolvedSenderEmailAdress, this.GetSMTPAddress(safeMailItem.SenderEmailAddress));
                this.newDoc.AppendItemValue(CDCOFileSettings.Instance.RptItm_From, safeMailItem.SenderName + SPACE + LESS_THAN + this.GetSMTPAddress(safeMailItem.SenderEmailAddress) + GREATER_THAN);
            }
            else
            {
                this.newDoc.AppendItemValue(CDCOFileSettings.Instance.RptItm_From, safeMailItem.SenderName + SPACE + LESS_THAN + safeMailItem.SenderEmailAddress + GREATER_THAN);
            }

            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.RptItm_SenderName, safeMailItem.SenderName);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.RptItm_SenderEmailAddress, safeMailItem.SenderEmailAddress);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.RptItm_SentOnBehalfOfName, safeMailItem.SentOnBehalfOfName);


            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.RptItm_ReceivedByName, safeMailItem.ReceivedByName);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.RptItm_ReceivedOnBehalfOfName, safeMailItem.ReceivedOnBehalfOfName);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.RptItm_ReplyRecipientNames, safeMailItem.ReplyRecipientNames);

            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.RptItm_Subject, reportItem.Subject);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.RptItm_CreationTime, reportItem.CreationTime);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.RptItm_EntryID, reportItem.EntryID);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.RptItm_ConversationID, reportItem.ConversationID);
            #endregion

            #region Create body rich text field
            NotesRichTextItem notesRichTextItem = this.newDoc.CreateRichTextItem(ConvergensSettings.CDCOFileSettings.Instance.RptItm_Body);

            if (!string.IsNullOrEmpty(reportItem.Body))
            {
                notesRichTextItem.AppendText(reportItem.Body);
            }
            #endregion

            #region Save email as EML & MSG
            try
            {
                switch (CDCOFileSettings.Instance.SaveAsType)
                {
                    case "1":
                        {
                            NotesRichTextItem saveAsTypeRichTextItem = this.newDoc.CreateRichTextItem(CDCOFileSettings.Instance.RptItm_EMLBody);
                            safeMailItem.SaveAs(Path.GetTempPath() + reportItem.EntryID.ToString() + ".eml", Redemption.RedemptionSaveAsType.olRFC822);
                            saveAsTypeRichTextItem.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, null, Path.GetTempPath() + "\\" + reportItem.EntryID.ToString() + ".eml", Path.GetTempPath() + "\\" + reportItem.EntryID.ToString() + ".eml");
                            File.Delete(Path.GetTempPath() + "\\" + reportItem.EntryID.ToString() + ".eml");
                            break;
                        }
                    case "2":
                        {
                            NotesRichTextItem saveAsTypeRichTextItem = this.newDoc.CreateRichTextItem(CDCOFileSettings.Instance.RptItm_MSGBody);
                            reportItem.SaveAs(Path.GetTempPath() + reportItem.EntryID.ToString() + ".msg", OL.OlSaveAsType.olMSGUnicode);
                            saveAsTypeRichTextItem.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, null, Path.GetTempPath() + "\\" + reportItem.EntryID.ToString() + ".msg", Path.GetTempPath() + "\\" + reportItem.EntryID.ToString() + ".msg");
                            File.Delete(Path.GetTempPath() + "\\" + reportItem.EntryID.ToString() + ".msg");
                            break;
                        }
                    case "99":
                        {
                            NotesRichTextItem saveAsTypeRichTextItemEml = this.newDoc.CreateRichTextItem(CDCOFileSettings.Instance.RptItm_EMLBody);
                            safeMailItem.SaveAs(Path.GetTempPath() + reportItem.EntryID.ToString() + ".eml", Redemption.RedemptionSaveAsType.olRFC822);
                            saveAsTypeRichTextItemEml.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, null, Path.GetTempPath() + "\\" + reportItem.EntryID.ToString() + ".eml", Path.GetTempPath() + "\\" + reportItem.EntryID.ToString() + ".eml");
                            File.Delete(Path.GetTempPath() + "\\" + reportItem.EntryID.ToString() + ".eml");

                            NotesRichTextItem saveAsTypeRichTextItemMsg = this.newDoc.CreateRichTextItem(CDCOFileSettings.Instance.RptItm_MSGBody);
                            reportItem.SaveAs(Path.GetTempPath() + reportItem.EntryID.ToString() + ".msg", OL.OlSaveAsType.olMSGUnicode);
                            saveAsTypeRichTextItemMsg.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, null, Path.GetTempPath() + "\\" + reportItem.EntryID.ToString() + ".msg", Path.GetTempPath() + "\\" + reportItem.EntryID.ToString() + ".msg");
                            File.Delete(Path.GetTempPath() + "\\" + reportItem.EntryID.ToString() + ".msg");
                            break;
                        }
                    default:
                        break;
                }

            }
            catch (Exception)
            {

                throw new ApplicationException("Mailen kunne ikke journaliseres!");
            }

            #endregion

            #region Save document to Domino
            isSaved = this.newDoc.Save(true, false);
            if (!isSaved)
            {
                throw new ApplicationException("Modtagelses kvitteringen kunne ikke journaliseres!");
            }
            else
            {
                Process.Start(this.newDoc.NotesURL);
                reportItem.Categories = "Journaliseret";
                reportItem.Save();
            }
            #endregion
        }

        public void journalizeMeetingItem(OL.MeetingItem meetingItem)
        {
            Type t = Type.GetTypeFromProgID("Redemption.SafeMailItem");
            SafeMailItem safeMailItem = (SafeMailItem)Activator.CreateInstance(t);
            safeMailItem.Item = meetingItem;


            bool isSaved = false;
            string tempString = string.Empty;

            // Create a Document
            this.CDCODB = this.GetMailDatabase(ConvergensSettings.CDCOFileSettings.Instance.SDHServerName);
            this.newDoc = this.CDCODB.CreateDocument();

            #region AppendItemValues "Form"
            this.newDoc.AppendItemValue("Form", ConvergensSettings.CDCOFileSettings.Instance.MtgItm_Form);

            #endregion

            #region Get SendTo field from Outlook and copy to document
            if (!string.IsNullOrEmpty(safeMailItem.To))
            {
                NotesItem tempItem = this.newDoc.ReplaceItemValue(ConvergensSettings.CDCOFileSettings.Instance.MtgItm_To, "");
                if (safeMailItem.Recipients.Count > 0)
                {
                    for (int i = 1; i <= safeMailItem.Recipients.Count; i++)
                    {
                        if (safeMailItem.Recipients[i].Type == 1)
                        {
                            Redemption.AddressEntry addressEntry = safeMailItem.Recipients[i].AddressEntry;
                            if (!addressEntry.Address.Contains("@"))
                            {
                                tempItem.AppendToTextList(addressEntry.Name + SPACE + LESS_THAN + this.GetSMTPAddress(addressEntry.Address) + GREATER_THAN);
                            }
                            else
                            {
                                tempItem.AppendToTextList(addressEntry.Name + SPACE + LESS_THAN + addressEntry.Address + GREATER_THAN);
                            }
                        }

                    }
                }

                tempItem.CopyItemToDocument(this.newDoc, ConvergensSettings.CDCOFileSettings.Instance.MtgItm_To);
                tempItem = null;
                tempString = string.Empty;
            }

            #endregion

            #region AppendItemValues "From" "Subject" "Date"
            if (!safeMailItem.SenderEmailAddress.Contains("@"))
	        {
                this.newDoc.AppendItemValue(CDCOFileSettings.Instance.MgtItm_ResolvedSenderEmailAdress, this.GetSMTPAddress(safeMailItem.SenderEmailAddress));
                this.newDoc.AppendItemValue(CDCOFileSettings.Instance.MtgItm_From, safeMailItem.SenderName + SPACE + LESS_THAN + this.GetSMTPAddress(safeMailItem.SenderEmailAddress) + GREATER_THAN);
            }
            else
            {
                this.newDoc.AppendItemValue(CDCOFileSettings.Instance.MtgItm_From, safeMailItem.SenderName + SPACE + LESS_THAN + safeMailItem.SenderEmailAddress + GREATER_THAN);
            }

            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.MgtItm_SenderName, safeMailItem.SenderName);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.MgtItm_SenderEmailAddress, safeMailItem.SenderEmailAddress);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.MgtItm_SentOnBehalfOfName, safeMailItem.SentOnBehalfOfName);

            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.MgtItm_ReceivedByName, safeMailItem.ReceivedByName);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.MgtItm_ReceivedOnBehalfOfName, safeMailItem.ReceivedOnBehalfOfName);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.MgtItm_ReplyRecipientNames, safeMailItem.ReplyRecipientNames);

            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.MtgItm_From, safeMailItem.SenderName + SPACE + LESS_THAN + this.GetSMTPAddress(safeMailItem.SenderEmailAddress) + GREATER_THAN);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.MtgItm_Subject, meetingItem.Subject);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.MtgItm_CreationTime, meetingItem.CreationTime);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.MtgItm_EntryID, meetingItem.EntryID);
            this.newDoc.AppendItemValue(CDCOFileSettings.Instance.MtgItm_ConversationID, meetingItem.ConversationID);
            #endregion

            #region Create body rich text field
            NotesRichTextItem notesRichTextItem = this.newDoc.CreateRichTextItem(CDCOFileSettings.Instance.MtgItm_Body);
            if (!string.IsNullOrEmpty(meetingItem.Body))
            {
                notesRichTextItem.AppendText(meetingItem.Body);
            }

            if (meetingItem.Attachments.Count > 0)
            {
                int k = 1;
                this.eMailAttachments.Clear();
                foreach (OL.Attachment attachment in meetingItem.Attachments)
                {
                    if (this.eMailAttachments.Contains(attachment.FileName))
                    {
                        string newFileName = attachment.FileName;

                        if (newFileName.Contains("."))
                        {
                            string underScor = "_";
                            int lastDot = newFileName.LastIndexOf('.');
                            newFileName = newFileName.Insert(lastDot, underScor + k.ToString());
                            this.eMailAttachments.Add(newFileName);
                            k++;
                        }
                        else
                        {
                            newFileName = newFileName + "_" + k.ToString();
                            this.eMailAttachments.Add(attachment.FileName);

                        }
                    }
                    else
                    {
                        this.eMailAttachments.Add(attachment.FileName);
                        k = 1;
                    }
                }

                k = 0;
                foreach (string attachmentsName in this.eMailAttachments)
                {
                    foreach (OL.Attachment attachment in meetingItem.Attachments)
                    {
                        if (attachmentsName == attachment.FileName)
                        {
                            try
                            {
                                File.SetAttributes(Path.GetTempPath() + "\\" + this.eMailAttachments[k].ToString(), FileAttributes.Normal);
                                File.Delete(Path.GetTempPath() + "\\" + this.eMailAttachments[k].ToString());
                            }
                            catch (Exception)
                            {
                                //Suspress all Exceptions
                            }

                            attachment.SaveAsFile(Path.GetTempPath() + "\\" + attachment.FileName);
                            File.Move(Path.GetTempPath() + "\\" + attachment.FileName, Path.GetTempPath() + "\\" + this.eMailAttachments[k].ToString());


                            notesRichTextItem.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, null, Path.GetTempPath() + "\\" + this.eMailAttachments[k].ToString(), Path.GetTempPath() + "\\" + this.eMailAttachments[k].ToString());
                            File.Delete(Path.GetTempPath() + "\\" + this.eMailAttachments[k].ToString());
                            k++;
                        }
                    }
                }
            }
            #endregion

            #region Save email as EML & MSG
            try
            {
                switch (CDCOFileSettings.Instance.SaveAsType)
                {
                    case "1":
                        {
                            NotesRichTextItem saveAsTypeRichTextItem = this.newDoc.CreateRichTextItem(CDCOFileSettings.Instance.MtgItm_EMLBody);
                            safeMailItem.SaveAs(Path.GetTempPath() + meetingItem.EntryID.ToString() + ".eml", Redemption.RedemptionSaveAsType.olRFC822);
                            saveAsTypeRichTextItem.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, null, Path.GetTempPath() + "\\" + meetingItem.EntryID.ToString() + ".eml", Path.GetTempPath() + "\\" + meetingItem.EntryID.ToString() + ".eml");
                            File.Delete(Path.GetTempPath() + "\\" + meetingItem.EntryID.ToString() + ".eml");
                            break;
                        }
                    case "2":
                        {
                            NotesRichTextItem saveAsTypeRichTextItem = this.newDoc.CreateRichTextItem(CDCOFileSettings.Instance.MtgItm_MSGBody);
                            meetingItem.SaveAs(Path.GetTempPath() + meetingItem.EntryID.ToString() + ".msg", OL.OlSaveAsType.olMSGUnicode);
                            saveAsTypeRichTextItem.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, null, Path.GetTempPath() + "\\" + meetingItem.EntryID.ToString() + ".msg", Path.GetTempPath() + "\\" + meetingItem.EntryID.ToString() + ".msg");
                            File.Delete(Path.GetTempPath() + "\\" + meetingItem.EntryID.ToString() + ".msg");
                            break;
                        }
                    case "99":
                        {
                            NotesRichTextItem saveAsTypeRichTextItemEml = this.newDoc.CreateRichTextItem(CDCOFileSettings.Instance.MtgItm_EMLBody);
                            safeMailItem.SaveAs(Path.GetTempPath() + meetingItem.EntryID.ToString() + ".eml", Redemption.RedemptionSaveAsType.olRFC822);
                            saveAsTypeRichTextItemEml.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, null, Path.GetTempPath() + "\\" + meetingItem.EntryID.ToString() + ".eml", Path.GetTempPath() + "\\" + meetingItem.EntryID.ToString() + ".eml");
                            File.Delete(Path.GetTempPath() + "\\" + meetingItem.EntryID.ToString() + ".eml");

                            NotesRichTextItem saveAsTypeRichTextItemMsg = this.newDoc.CreateRichTextItem(CDCOFileSettings.Instance.MtgItm_MSGBody);
                            meetingItem.SaveAs(Path.GetTempPath() + meetingItem.EntryID.ToString() + ".msg", OL.OlSaveAsType.olMSGUnicode);
                            saveAsTypeRichTextItemMsg.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, null, Path.GetTempPath() + "\\" + meetingItem.EntryID.ToString() + ".msg", Path.GetTempPath() + "\\" + meetingItem.EntryID.ToString() + ".msg");
                            File.Delete(Path.GetTempPath() + "\\" + meetingItem.EntryID.ToString() + ".msg");
                            break;
                        }
                    default:
                        break;
                }

            }
            catch (Exception)
            {

                throw new ApplicationException("Mailen kunne ikke journaliseres!");
            }

            #endregion

            #region Save document to Domino
            isSaved = this.newDoc.Save(true, false);
            if (!isSaved)
            {
                throw new ApplicationException("Modtagelses kvitteringen kunne ikke journaliseres!");
            }
            else
            {
                Process.Start(this.newDoc.NotesURL);
                meetingItem.Categories = "Journaliseret";
                meetingItem.Save();
            }
            #endregion
        }

        public bool FindSDHProfilDB()
        {

            NotesDbDirectory notesDbDirectory;

            try
            {
                if (profildb == null || !profildb.IsOpen)
                {
                    notesDbDirectory = this.notesSession.GetDbDirectory(ConvergensSettings.CDCOFileSettings.Instance.SDHServerName);
                    profildb = notesDbDirectory.OpenDatabase("SDHtools\\SDHProfil.nsf", true);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Der er desværre ikke adgang til SDH systemet i øjeblikket.\nPrøv venligst igen lidt senere.\n\nServer: " + ConvergensSettings.CDCOFileSettings.Instance.SDHServerName + "\nDatabase: " + "SDHProfil.nsf" + "\n\nSystem besked:\n" + ex.Message);
            }

            return true;
        }

        public bool FindSDHEmneordDB()
        {

            NotesDbDirectory notesDbDirectory;

            try
            {
                if (emneorddb == null || !emneorddb.IsOpen)
                {
                    notesDbDirectory = this.notesSession.GetDbDirectory(ConvergensSettings.CDCOFileSettings.Instance.SDHServerName);
                    emneorddb = notesDbDirectory.OpenDatabase("SDHtools\\emneord.nsf", true);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Der er desværre ikke adgang til Emneords databasen i øjeblikket.\nPrøv venligst igen lidt senere.\n\nServer: " + ConvergensSettings.CDCOFileSettings.Instance.SDHServerName + "\nDatabase: " + "Emneord.nsf" + "\n\nSystem besked:\n" + ex.Message);
            }

            return true;
        }

        public bool FindMiniNabDB()
        {

            NotesDbDirectory notesDbDirectory;

            try
            {
                if (mininabdb == null || !mininabdb.IsOpen)
                {
                    notesDbDirectory = this.notesSession.GetDbDirectory(ConvergensSettings.CDCOFileSettings.Instance.SDHServerName);
                    //notesDbDirectory = this.notesSession.GetDbDirectory(""); //debug with local mininab
                    mininabdb = notesDbDirectory.OpenDatabase("mininab.nsf", true);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Der er desværre ikke adgang til SDH systemet i øjeblikket.\nPrøv venligst igen lidt senere.\n\nServer: " + ConvergensSettings.CDCOFileSettings.Instance.SDHServerName + "\nDatabase: " + "mininab.nsf" + "\n\nSystem besked:\n" + ex.Message);
            }

            return true;
        }

        public List<string> FindSDHDBS()
        {
            List<string> ar = this.DBColumn(this.profildb, "lk.efter.enhed", 1);

           return ar; 
        }

        public string[] LoadCaseOfficers()
        {
            //List<string> ar = this.DBColumn(this.mininabdb, "SDHNAVNE", 1);
            string[] ar = this.DBColumnFormula(this.mininabdb, "SDHNAVNE", 1);

            //ar.Add("Mounir Akhiat");
            //ar.Add("Jörg Asmussen");
            return ar;
        }

        public string[] LoadMailInvitRigts()
        {
            string[] ar = this.DBColumnFormula(this.mininabdb, "SDHNAVNEOGGROUP", 1);

            return ar;
        }

        public List<string> LoadSubjectHeading(string viewName)
        {
            List<string> ar = this.DBColumn(this.emneorddb, viewName, 0);

            return ar;
        }

        private List<string> DBColumn(NotesDatabase db, string viewName, int colNum)
        {
            NotesDocument doc;
            NotesView view;

            List<object> o = new List<object>();
            List<string> res = new List<string>();
            Array array;

            view = db.GetView(viewName);
            doc = view.GetFirstDocument();

            int i = 0;
            while (doc != null)
            {
                o.Add((Array)doc.ColumnValues);
                array = (Array)o[i];
                res.Add((string)array.GetValue(colNum - 1));
                doc = view.GetNextDocument(doc);
                i++;
            }

            doc = null;
            view = null;
            array = null;

            return res;
        }

        private string[] DBColumnFormula(NotesDatabase db, string viewName, int colNum)
        {
            try
            {
                NotesDatabase notesDatabase;
                NotesDbDirectory notesDbDirectory;
                List<object> objectArr = new List<object>();
                List<string> strArr = new List<string>();
                notesDbDirectory = this.notesSession.GetDbDirectory(db.Server);

                notesDatabase = notesDbDirectory.OpenMailDatabase();
                NotesDocument ndoc = notesDatabase.CreateDocument();
                string filePath = db.FilePath;
                string pFormula = "@DbColumn(\"\";\"" + db.Server+ "\":\"" + filePath.Replace("\\", "\\\\") + "\";\""+ viewName  + "\";"+ colNum.ToString() + ")";
                try
                {
                    objectArr.AddRange((object[])this.notesSession.Evaluate(pFormula, ndoc));

                }
                catch (COMException cx)
                {
                    if (cx.ErrorCode == -2147217427)
                    {
                        objectArr.AddRange((object[])this.notesSession.Evaluate(pFormula, ndoc));
                    }
                }

                string[] stringarr = ((IEnumerable)objectArr).Cast<object>()
                     .Select(x => x.ToString())
                     .ToArray();


                return (stringarr);
            }
            catch (Exception)
            {
                throw;
            }
        }

        public string GetSDHEmneOrdJaNej(string sdhName)
        {
            try
            {
                NotesDbDirectory notesDbDirectory;
                NotesView view;
                NotesDocument doc;

                notesDbDirectory = this.notesSession.GetDbDirectory(ConvergensSettings.CDCOFileSettings.Instance.SDHServerName);
                view = this.profildb.GetView("lk.efter.enhed");
                doc = view.GetDocumentByKey(sdhName);

                Array repArr = (Array)doc.GetItemValue("SDHEmneord");
                return (string)repArr.GetValue(0);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public List<Array> GetVariant1Emneord(string sdhName, string UNID)
        {
            try
            {
                List<Array> Variant1Emneord = new List<Array>(10);
                NotesDbDirectory notesDbDirectory;
                NotesDatabase db;
                NotesView view;
                NotesDocument profiledoc;
                NotesDocument sdhdoc;

                notesDbDirectory = this.notesSession.GetDbDirectory(ConvergensSettings.CDCOFileSettings.Instance.SDHServerName);
                view = this.profildb.GetView("lk.efter.enhed");
                profiledoc = view.GetDocumentByKey(sdhName);

                Array repArr = (Array)profiledoc.GetItemValue("Sdhreplicaid");
                db = notesDbDirectory.OpenDatabaseByReplicaID((string)repArr.GetValue(0));

                sdhdoc = db.GetDocumentByUNID(UNID);

                if (sdhdoc != null)
                {
                    Variant1Emneord.Add((Array)sdhdoc.GetItemValue("OutputField1"));
                    Variant1Emneord.Add((Array)sdhdoc.GetItemValue("OutputField2"));
                    Variant1Emneord.Add((Array)sdhdoc.GetItemValue("OutputField3"));
                    Variant1Emneord.Add((Array)sdhdoc.GetItemValue("OutputField4"));
                    Variant1Emneord.Add((Array)sdhdoc.GetItemValue("OutputField5"));
                    Variant1Emneord.Add((Array)sdhdoc.GetItemValue("Subject"));
                    Variant1Emneord.Add((Array)sdhdoc.GetItemValue("SagBeskyttet"));
                    Variant1Emneord.Add((Array)sdhdoc.GetItemValue("Reader1"));
                    Variant1Emneord.Add((Array)sdhdoc.GetItemValue("Sagsdele"));
                }

                return Variant1Emneord;

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public string GetSDHDatabaseFilePath(string sdhName)
        {
            try
            {
                NotesDbDirectory notesDbDirectory;
                NotesView view;
                NotesDocument doc;

                notesDbDirectory = this.notesSession.GetDbDirectory(ConvergensSettings.CDCOFileSettings.Instance.SDHServerName);
                view = this.profildb.GetView("lk.efter.enhed");
                doc = view.GetDocumentByKey(sdhName);

                Array repArr = (Array)doc.GetItemValue("sdhfilnavn");

                return (string)repArr.GetValue(0);

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public NotesDatabase GetSDHDatabase(string sdhName)
        {
            try
            {
                NotesDbDirectory notesDbDirectory;
                NotesDatabase db;
                NotesView view;
                NotesDocument doc;

                notesDbDirectory = this.notesSession.GetDbDirectory(ConvergensSettings.CDCOFileSettings.Instance.SDHServerName);
                view = this.profildb.GetView("lk.efter.enhed");
                doc = view.GetDocumentByKey(sdhName);

                Array repArr = (Array)doc.GetItemValue("Sdhreplicaid");
                db = notesDbDirectory.OpenDatabaseByReplicaID((string)repArr.GetValue(0));

                if (db.IsOpen)
                {
                    return db;
                }
                else
                {
                    throw new ApplicationException("NotesDatabase: " + db.FileName + " not open in getSDHDatabase");
                }

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public List<object> FreeCatCEvaluate(string serverName, string filePath)
        {
            try
            {
                NotesDatabase notesDatabase;
                NotesDbDirectory notesDbDirectory;
                List<object> objectArr = new List<object>();
                List<string> strArr = new List<string>();
                notesDbDirectory = this.notesSession.GetDbDirectory(serverName);

                notesDatabase = notesDbDirectory.OpenMailDatabase();
                NotesDocument ndoc = notesDatabase.CreateDocument();
                string pFormula = "@Unique(@Trim(@DbLookup(\"\";\"UVM1/UVM\":\""+filePath.Replace("\\","\\\\")+"\";\"admin.fri.kategori\";@Name([CN];@Username);2;[FAILSILENT])))";

                try
                {
                    objectArr.AddRange((object[])this.notesSession.Evaluate(pFormula, ndoc));
                }
                catch (COMException cx)
                {
                    if (cx.ErrorCode == -2147217427)
                    {
                        objectArr.AddRange((object[])this.notesSession.Evaluate(pFormula, ndoc));
                    }
                }

                return (objectArr);
            }
            catch (Exception)
            {
                throw;
            }
        }

        public List<object> GetCaseAreaVarivant2(string sdhName)
        {
            try
            {
                NotesDatabase notesDatabase;
                NotesDbDirectory notesDbDirectory;
                List<object> objectArr = new List<object>();
                List<string> strArr = new List<string>();
                notesDbDirectory = this.notesSession.GetDbDirectory(string.Empty);

                notesDatabase = notesDbDirectory.OpenMailDatabase();
                NotesDocument ndoc = notesDatabase.CreateDocument();
                // @DbLookup( """":""NoCache"";""UVM1/Uvm"":""SDH\\testsdh.nsf"" ; ""admin.emne"" ; """+  strReplicaID +  """ ; 2)"
                string pFormula = "@DbLookup(\"\";\"UVM1/UVM\":\"SDHTOOLS\\\\SDHprofil.nsf\";\"admin.emne\";\"" + this.GetDBReplicaIdBySDHName(sdhName) + "\";2;[FAILSILENT])";

                try
                {
                    objectArr.AddRange((object[])this.notesSession.Evaluate(pFormula, ndoc));
                }
                catch (COMException cx)
                {
                    if (cx.ErrorCode == -2147217427)
                    {
                        objectArr.AddRange((object[])this.notesSession.Evaluate(pFormula, ndoc));
                    }
                }

                return (objectArr);
            }
            catch (Exception)
            {
                throw;
            }
        }

        public NotesView GetNotesView(NotesDatabase notesDatabase, string viewName)
        {
            NotesView notesView;

            try
            {
                if (notesDatabase.IsOpen)
                {
                    notesView = notesDatabase.GetView(viewName);
                    return notesView;
                }
                else
                {
                    throw new ApplicationException("NotesDatabase: " + notesDatabase.FileName + " not open in GetNotesView");
                }

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public NotesView GetNotesViewByCategory(NotesDatabase notesDatabase, string viewName, string Category)
        {
            NotesView notesView;

            try
            {
                notesView = notesDatabase.GetView(viewName);
                return notesView;

            }
            catch (Exception ex)
            {

                throw new Exception(ex.Message);
            }
        }

        //public DataSet GetViewEntryCollectionToDataSet(NotesView notesView)
        //{
        //    return GetViewEntryCollectionToDataSet(notesView.AllEntries, notesView);
        //}
        //public DataSet GetViewEntryCollectionToDataSet(NotesViewEntryCollection notesViewEntryCollection, NotesView notesView)
        //{
        //    DataSet dataSet = new DataSet();
        //    dataSet.Tables.Add("NotesDataSet");
        //    DataRow dataRow;
        //    NotesViewEntry entry;
        //    int n;
        //    try
        //    {
        //        if (notesViewEntryCollection == null)
        //        {
        //            throw new ArgumentNullException("Argument NotesViewEntryCollection missing.");
        //        }
        //        if (notesView == null)
        //        {
        //            throw new ArgumentNullException("Argument NotesView missing.");
        //        }

        //        object columnTitles = notesView.ColumnNames;
        //        Array columnTitlesArray = (Array)columnTitles;

        //        string columnTitle = string.Empty;
        //        for (int i = 0; i < notesView.ColumnCount; i++)
        //        {
        //            columnTitle = (string)columnTitlesArray.GetValue(i);
        //            columnTitle = columnTitle.Trim();
        //            dataSet.Tables[0].Columns.Add(columnTitle.Replace(' ', '_'));
        //        }

        //        dataSet.Tables[0].Columns.Add("UNID");
        //        dataSet.Tables[0].Columns["UNID"].ColumnMapping = MappingType.Hidden;

        //        entry = notesViewEntryCollection.GetFirstEntry();

        //        object columnValues = entry.ColumnValues;
        //        Array columnArray = (Array)columnValues;
        //        while (entry != null)
        //        {
        //            dataRow = dataSet.Tables[0].NewRow();
        //            for (n = 0; n < columnArray.Length; n++)
        //            {
        //                columnValues = entry.ColumnValues;
        //                columnArray = (Array)columnValues;
        //                dataRow[n] = columnArray.GetValue(n);
        //            }
        //            dataRow[n] = entry.UniversalID;

        //            dataSet.Tables[0].Rows.Add(dataRow);
        //            entry = notesViewEntryCollection.GetNextEntry(entry);
        //        }

        //        return dataSet;

        //    }
        //    catch (Exception ex)
        //    {
        //        throw new Exception(ex.Message);
        //    }

        //}

        public DataTable GetMyActiveCases(string viewname, string sdhname)
        {
            DataTable dataTable = new DataTable();
            dataTable.BeginLoadData();

            NotesDatabase db = DominoConnector.Default.GetSDHDatabase(sdhname);
            NotesView view = DominoConnector.Default.GetNotesView(db, viewname);
            NotesViewEntryCollection nvec = view.GetAllEntriesByKey(DominoConnector.Default.NotesSession.CommonUserName);
            //NotesViewEntryCollection nvec = view.GetAllEntriesByKey("Kurt E. Nielsen");

            dataTable = DominoConnector.Default.GetViewEntryCollectionToDataTable(nvec, view);
            dataTable.Columns[0].ColumnMapping = MappingType.Hidden;

            db = null;
            view = null;
            nvec = null;

            dataTable.EndLoadData();

            return dataTable;
        }

        public DataTable GetMyActiveIncomingDocs(string viewname, string sdhname)
        {
            DataTable dataTable = new DataTable();
            dataTable.BeginLoadData();

            NotesDatabase db = DominoConnector.Default.GetSDHDatabase(sdhname);
            NotesView view = DominoConnector.Default.GetNotesView(db, viewname);
            NotesViewEntryCollection nvec = view.GetAllEntriesByKey(DominoConnector.Default.NotesSession.CommonUserName);
            //NotesViewEntryCollection nvec = view.GetAllEntriesByKey("Anders Gram Mygind");

            dataTable = DominoConnector.Default.GetViewEntryCollectionToDataTable(nvec, view);
            dataTable.Columns[0].ColumnMapping = MappingType.Hidden;

            dataTable.EndLoadData();

            return dataTable;
        }
      
        public DataTable GetActiveCasesByCaseOfficer(string viewname, string sdhname)
        {
            DataTable dataTable = new DataTable();
            dataTable.BeginLoadData();

            NotesDatabase db = DominoConnector.Default.GetSDHDatabase(sdhname);
            NotesView view = DominoConnector.Default.GetNotesView(db, viewname);

            dataTable = DominoConnector.Default.GetViewEntryCollectionToDataTable(view);
            //dataTable.Columns[0].ColumnMapping = MappingType.Hidden;

            dataTable.EndLoadData();

            return dataTable;
        }

        public DataTable GetActiveIncomingByCaseOfficer(string viewname, string sdhname)
        {
            DataTable dataTable = new DataTable();
            dataTable.BeginLoadData();

            NotesDatabase db = DominoConnector.Default.GetSDHDatabase(sdhname);
            NotesView view = DominoConnector.Default.GetNotesView(db, viewname);

            dataTable = DominoConnector.Default.GetViewEntryCollectionToDataTable(view);
            //dataTable.Columns[0].ColumnMapping = MappingType.Hidden;

            dataTable.EndLoadData();
            return dataTable;
        }

        public DataTable GetAllActiveCases(string viewname, string sdhname)
        {
            DataTable dataTable = new DataTable();
            dataTable.BeginLoadData();

            NotesDatabase db = DominoConnector.Default.GetSDHDatabase(sdhname);
            NotesView view = DominoConnector.Default.GetNotesView(db, viewname);

            dataTable = DominoConnector.Default.GetViewEntryCollectionToDataTable(view);
            //dataTable.Columns[0].ColumnMapping = MappingType.Hidden;

            dataTable.EndLoadData();

            return dataTable;
        }

        public DataTable GetAllActiveIncoming(string viewname, string sdhname)
        {
            DataTable dataTable = new DataTable();
            dataTable.BeginLoadData();

            NotesDatabase db = DominoConnector.Default.GetSDHDatabase(sdhname);
            NotesView view = DominoConnector.Default.GetNotesView(db, viewname);

            dataTable = DominoConnector.Default.GetViewEntryCollectionToDataTable(view);
            //dataTable.Columns[0].ColumnMapping = MappingType.Hidden;

            dataTable.EndLoadData();

            return dataTable;
        }

        public DataTable GetActiveCasesByOffice(string viewname, string sdhname)
        {
            DataTable dataTable = new DataTable();
            dataTable.BeginLoadData();

            NotesDatabase db = DominoConnector.Default.GetSDHDatabase(sdhname);
            NotesView view = DominoConnector.Default.GetNotesView(db, viewname);

            dataTable = DominoConnector.Default.GetViewEntryCollectionToDataTable(view);
            dataTable.Columns[0].ColumnMapping = MappingType.Hidden;

            dataTable.EndLoadData();

            return dataTable;
        }

        public DataTable GetActiveIncommingDocsByOffice(string viewname, string sdhname)
        {
            DataTable dataTable = new DataTable();

            NotesDatabase db = DominoConnector.Default.GetSDHDatabase(sdhname);
            NotesView view = DominoConnector.Default.GetNotesView(db, viewname);

            dataTable = DominoConnector.Default.GetViewEntryCollectionToDataTable(view);
            //dataTable.Columns[0].ColumnMapping = MappingType.Hidden;

            return dataTable;
        }

        public string GetSDHCaseDocumentUNIDByCaseNumber(string casenumber, string sdhname)
        {
            try
            {
                List<Array> returnlist = new List<Array>(10);
                NotesDbDirectory notesDbDirectory;
                NotesDatabase db;
                NotesView view;
                NotesDocument profiledoc;
                NotesDocument sdhdoc;

                notesDbDirectory = this.notesSession.GetDbDirectory(ConvergensSettings.CDCOFileSettings.Instance.SDHServerName);
                view = this.profildb.GetView("lk.efter.enhed");
                profiledoc = view.GetDocumentByKey(sdhname);

                Array repArr = (Array)profiledoc.GetItemValue("Sdhreplicaid");
                db = notesDbDirectory.OpenDatabaseByReplicaID((string)repArr.GetValue(0));

                view = db.GetView("pick.sag.alle");

                sdhdoc = view.GetDocumentByKey(casenumber,true);

                if (sdhdoc == null)
                {
                    return string.Empty;
                }
                else
                {
                    return sdhdoc.UniversalID;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public string GetDBReplicaIdBySDHName(string sdhname)
        {
            try
            {
                NotesDbDirectory notesDbDirectory;
                NotesView view;
                NotesDocument profiledoc;

                notesDbDirectory = this.notesSession.GetDbDirectory(ConvergensSettings.CDCOFileSettings.Instance.SDHServerName);
                view = this.profildb.GetView("lk.efter.enhed");
                profiledoc = view.GetDocumentByKey(sdhname);

                Array repArr = (Array)profiledoc.GetItemValue("Sdhreplicaid");
                string replicaId = (string)repArr.GetValue(0);

                if (replicaId == null)
                {
                    return string.Empty;
                }
                else
                {
                    return replicaId;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        
        public DataTable GetActiveIncomingByCase(string viewname, string sdhname, string caseNum)
        {
            DataTable dataTable = new DataTable();
            dataTable.BeginLoadData();

            NotesDatabase db = DominoConnector.Default.GetSDHDatabase(sdhname);
            NotesView view = DominoConnector.Default.GetNotesView(db, viewname);
            NotesViewEntryCollection nvec = view.GetAllEntriesByKey(caseNum);

            dataTable = DominoConnector.Default.GetViewEntryCollectionToDataTable(nvec, view);
            dataTable.Columns[0].ColumnMapping = MappingType.Hidden;

            dataTable.EndLoadData();

            return dataTable;
        }

        public DataTable GetSubjectHeadings(string viewname, string category)
        {
            DataTable dataTable = new DataTable();
            dataTable.BeginLoadData();

            if (DominoConnector.Default.FindSDHEmneordDB())
            {
                NotesView view = DominoConnector.Default.GetNotesView(this.emneorddb, viewname);

                if (category.Equals(string.Empty))
                {
                    dataTable = DominoConnector.Default.GetViewEntryCollectionToDataTable(view);

                }
                else
                {
                    dataTable = DominoConnector.Default.GetViewNavigatorToDataTable(view, category);

                    //NotesViewEntryCollection nvec = view.GetAllEntriesByKey(category);
                    //dataTable = DominoConnector.Default.GetViewEntryCollectionToDataTable(nvec, view);
                }

                //NotesViewEntryCollection nvec = view.GetAllEntriesByKey(DominoConnector.Default.NotesSession.CommonUserName);
                //dataTable.Columns[0].ColumnMapping = MappingType.Hidden;
            }

            dataTable.EndLoadData();

            return dataTable;
        }

        public SortedDictionary<string, string> GetSubjectHeadingsHashtable(string viewname, string category)
        {
            SortedDictionary<string, string> list = new SortedDictionary<string, string>();

            if (DominoConnector.Default.FindSDHEmneordDB())
            {
                NotesView view = DominoConnector.Default.GetNotesView(this.emneorddb, viewname);

                if (category.Equals(string.Empty))
                {
                    list = DominoConnector.Default.GetViewEntryCollectionToList(view);

                }
                else
                {
                    //NotesViewEntryCollection nvec = view.GetAllEntriesByKey(category);
                    //dataTable = DominoConnector.Default.GetViewEntryCollectionToDataTable(nvec, view);
                }

                //NotesViewEntryCollection nvec = view.GetAllEntriesByKey(DominoConnector.Default.NotesSession.CommonUserName);
                //dataTable.Columns[0].ColumnMapping = MappingType.Hidden;
            }


            return list;
        }

        public DataTable GetViewEntryCollectionToDataTable(NotesView notesView)
        {
            return GetViewEntryCollectionToDataTable(notesView.AllEntries, notesView);
        }

        public DataTable GetViewEntryCollectionToDataTable(NotesView notesView, string category)
        {
            NotesViewEntryCollection coll = notesView.GetAllEntriesByKey(category);
            return GetViewEntryCollectionToDataTable(coll, notesView);
        }

        public DataTable GetViewEntryCollectionToDataTable(NotesViewEntryCollection notesViewEntryCollection, NotesView notesView)
        {
            DataTable dataTable = new DataTable();
            dataTable.BeginLoadData();

            NotesViewEntry entry;
            DataRow dataRow;
            int n;
            try
            {
                if (notesViewEntryCollection == null)
                {
                    throw new ArgumentNullException("Argument NotesViewEntryCollection missing.");
                }
                if (notesView == null)
                {
                    throw new ArgumentNullException("Argument NotesView missing.");
                }

                object columnTitles = notesView.ColumnNames;
                Array columnTitlesArray = (Array)columnTitles;

                for (int i = 0; i < notesView.ColumnCount; i++)
                {
                    dataTable.Columns.Add((string)columnTitlesArray.GetValue(i));
                }

                dataTable.Columns.Add("UNID");
                //dataTable.Columns["UNID"].ColumnMapping = MappingType.Hidden;

                if (notesViewEntryCollection.Count > 0)
                {
                    entry = notesViewEntryCollection.GetFirstEntry();


                    Array columnValues = (Array)entry.ColumnValues;
                    //Array columnArray = (Array)columnValues;
                    int i = 0;

                    while (entry != null)
                    {
                        dataRow = dataTable.NewRow();
                        for (n = 0; n < columnValues.Length; n++)
                        {
                            columnValues = (Array)entry.ColumnValues;
                            //columnArray = (Array)columnValues;
                            dataRow[n] = columnValues.GetValue(n);
                        }
                        dataRow[n] = entry.UniversalID;

                        dataTable.Rows.Add(dataRow);
                        entry = notesViewEntryCollection.GetNextEntry(entry);
                        i++;
                    }
                }
                dataTable.EndLoadData();

                return dataTable;

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public SortedDictionary<string, string> GetViewEntryCollectionToList(NotesView notesView)
        {
            return GetViewEntryCollectionToHashList(notesView.AllEntries, notesView);
        }

        public SortedDictionary<string, string> GetViewEntryCollectionToHashList(NotesViewEntryCollection notesViewEntryCollection, NotesView notesView)
        {
            SortedDictionary<string, string> list = new SortedDictionary<string, string>();

            NotesViewEntry entry;

            try
            {
                if (notesViewEntryCollection == null)
                {
                    throw new ArgumentNullException("Argument NotesViewEntryCollection missing.");
                }
                if (notesView == null)
                {
                    throw new ArgumentNullException("Argument NotesView missing.");
                }

                if (notesViewEntryCollection.Count > 0)
                {
                    entry = notesViewEntryCollection.GetFirstEntry();
                     
                    Array columnValues = (Array)entry.ColumnValues;
                    //Array columnArray = (Array)columnValues;
                    while (entry != null)
                    {
                        columnValues = (Array)entry.ColumnValues;
                        try
                        {
                            list.Add((string)columnValues.GetValue(0), (string)columnValues.GetValue(1));
                        }
                        catch (Exception)
                        {
                            // Ignore duplicate keys
                            entry = notesViewEntryCollection.GetNextEntry(entry);
                            continue;    
                        }
                        entry = notesViewEntryCollection.GetNextEntry(entry);
                    }
                }

                return list;

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public DataTable GetViewNavigatorToDataTable(NotesView notesView, string category)
        {
      
            DataTable dataTable = new DataTable();
            dataTable.BeginLoadData();

            notesView.AutoUpdate = false;

            NotesViewNavigator viewnavigator = notesView.CreateViewNavFromCategory(category);
            NotesViewEntry entry;
            DataRow dataRow;
            int n;
            try
            {
                if (notesView == null)
                {
                    throw new ArgumentNullException("Argument NotesView missing.");
                }

                object columnTitles = notesView.ColumnNames;
                Array columnTitlesArray = (Array)columnTitles;

                for (int i = 0; i < notesView.ColumnCount; i++)
                {
                    dataTable.Columns.Add((string)columnTitlesArray.GetValue(i));
                }

                dataTable.Columns.Add("UNID");
                dataTable.Columns["UNID"].ColumnMapping = MappingType.Hidden;

                entry = viewnavigator.GetFirst();

                if (!entry.Equals(null))
                {
                    
                    Array columnValues = (Array)entry.ColumnValues;
                    //Array columnArray = (Array)columnValues;

                    while (entry != null)
                    {
                        dataRow = dataTable.NewRow();
                        for (n = 0; n < columnValues.Length; n++)
                        {
                            columnValues = (Array)entry.ColumnValues;
                            //columnArray = (Array)columnValues;
                            dataRow[n] = columnValues.GetValue(n);
                        }
                        dataRow[n] = entry.UniversalID;

                        dataTable.Rows.Add(dataRow);
                        entry = viewnavigator.GetNext(entry);
                    }
                }

                dataTable.EndLoadData();
                
                return dataTable;

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        private string GetSMTPFromMessageHeaders(string STMPtransportMessageHeaders)
        {
            try
            {
                if (string.IsNullOrEmpty(STMPtransportMessageHeaders))
                {
                    return string.Empty;
                }

                if (STMPtransportMessageHeaders.IndexOf('<') == 0)
                {
                    return STMPtransportMessageHeaders;
                }
                else
                {

                    //start of email address field value
                    string fromColon = "<";
                    int fromIndex = STMPtransportMessageHeaders.IndexOf(fromColon) - 1;
                    if (fromIndex == -1) { throw new Exception("Fejl i getSMTPFromMessageHeaders" + fromColon + "\""); }
                    fromIndex += fromColon.Length;

                    //end of email address field value
                    char lineSeparator = '>';
                    int toIndex = STMPtransportMessageHeaders.IndexOf(lineSeparator, fromIndex) + 1;
                    if (toIndex == -1) { throw new Exception("Fejl i getSMTPFromMessageHeaders" + ((byte)lineSeparator).ToString("X2") + "'"); }

                    return STMPtransportMessageHeaders.Substring(fromIndex, toIndex - fromIndex).Trim();
                }
            }
            catch (Exception e)
            {
                throw new Exception("Fejl i getSMTPFromMessageHeaders", e);
            }
        }

        private string GetEmailFromMessageHeaders(string transportMessageHeaders)
        {
            try
            {
                if (string.IsNullOrEmpty(transportMessageHeaders))
                {
                    return string.Empty;
                }

                //start of email address field value
                string fromColon = "From:";
                int fromIndex = transportMessageHeaders.IndexOf(fromColon);
                if (fromIndex == -1) { throw new Exception("Fejl i getEmailFromMessageHeaders." + fromColon + "\""); }
                fromIndex += fromColon.Length;

                //end of email address field value
                char lineSeparator = '\x0D';
                int toIndex = transportMessageHeaders.IndexOf(lineSeparator, fromIndex);
                if (toIndex == -1)
                {
                    throw new Exception("Fejl i getEmailFromMessageHeaders." + ((byte)lineSeparator).ToString("X2") + "'");
                }

                return transportMessageHeaders.Substring(fromIndex, toIndex - fromIndex).Trim();
            }
            catch (Exception e)
            {
                throw new Exception("Denne mail kan ikke journaliseres. \nMailen har ingen informationer i transport headeren. \nKontakt venligst brugerservice.", e);
            }
        }

        private string removeCommaAndReverse(string senderName)
        {
            //Marzouk, Eiman
            if (senderName.Contains(","))
            {
                string[] temp = senderName.Split(',');
                return temp[1].Trim() + " " + temp[0].Trim();

            }
            else
            {
                return senderName;
            }
        }

        #region RTF support beta
        private string GetRTF(OL.MailItem mailItem)
        {
            string messageStoreID = string.Empty;
            string theFolderStorID = string.Empty;
            OL.Application app = new OL.Application();
            object objMessageStore = mailItem.Parent;
            if (!(objMessageStore is OL.MAPIFolder))
            {
                return null;
            }

            OL.MAPIFolder messageStore = (OL.MAPIFolder)objMessageStore;
            messageStoreID = messageStore.EntryID;


            // Loop over the Stores
            foreach (OL.MAPIFolder myStore in app.Session.Folders)
            {
                // Loop over the Toplevel Folders
                foreach (OL.MAPIFolder myFolder in myStore.Folders)
                {
                    // Check for the Inbox Name
                    // Could read the Names from Configfile
                    if (myFolder.Name == "Inbox")
                    {
                        //Remember the EntryID and StoreID
                        theFolderStorID = myFolder.StoreID;
                        //myFolderIDs.Add(myFolder.EntryID, myFolder.StoreID);
                    }
                }
            }


            //IntPtr pRtfText;
            //try
            //{
            //int rftTextLength = 0;
            //string rtfText;
            //pRtfText = Marshal.StringToCoTaskMemUni(rtfText);
            string rtfText = new string(' ', 100000);
            int bRet = readrtf(mailItem.Application.Session.CurrentUser.Name, mailItem.EntryID, theFolderStorID, ref rtfText/*ref pRtfText, ref rftTextLength*/);
            if (bRet != 0)
            {
                return null;
            }
            //rtfText = Marshal.PtrToStringUni(pRtfText);
            //  return rtfText.Substring(0, bRet);
            // }
            // catch (System.Exception)
            //{
            //suppress
            // }
            // finally
            // {
            //if (pRtfText != null)
            //{
            //    Marshal.FreeCoTaskMem(pRtfText);
            //}
            // }
            return rtfText;
        }
        #endregion

        #region HTML support
        private void AppendNotesRichTextItem(OL.MailItem mailItem)
        {
            //Det er stadige ikke et rigtigt design!!
            //Og NEJ Jesper. Der skal ikke kontrollers for om der er noget i body. Der gjordt en gang
            //and I know its a hack
            NotesRichTextItem notesRichTextItem = this.newDoc.CreateRichTextItem("Body");
            notesRichTextItem.AppendText(mailItem.Body);
            notesRichTextItem.AddNewLine(2, true);

            foreach (OL.Attachment attachment in mailItem.Attachments)
            {
                this.eMailAttachments.Add(attachment.FileName);
            }

            foreach (string attachmentsName in this.eMailAttachments)
            {
                foreach (OL.Attachment attachment in mailItem.Attachments)
                {
                    if (attachmentsName == attachment.FileName)
                    {
                        try
                        {
                            File.SetAttributes(Path.GetTempPath() + "\\" + attachment.FileName, FileAttributes.Normal);
                            File.Delete(Path.GetTempPath() + "\\" + attachment.FileName);
                        }
                        catch (Exception)
                        {
                            //Suspress all Exceptions
                        }

                        attachment.SaveAsFile(Path.GetTempPath() + "\\" + attachment.FileName);

                        notesRichTextItem.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, null, Path.GetTempPath() + "\\" + attachment.FileName, Path.GetTempPath() + "\\" + attachment.FileName);
                        File.Delete(Path.GetTempPath() + "\\" + attachment.FileName);
                    }
                }
            }

        }

        //private string[] createTempHTMLEncoding(OL.MailItem mailItem)
        //{
        //    string[] HTMLEndcoding = new string[3];
        //    HTMLEndcoding[0] = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

        //    if (!System.IO.File.Exists(HTMLEndcoding[0]))
        //    {
        //        using (FileStream fileStream = File.Create(HTMLEndcoding[0]))
        //        {
        //            Encoding encoding = Encoding.GetEncoding(mailItem.InternetCodepage);
        //            string rtf = this.GetRTF(mailItem);
        //            fileStream.Write(encoding.GetBytes(rtf), 0, rtf.Trim().Length);
        //            fileStream.Flush();
        //            fileStream.Close();
        //            HTMLEndcoding[1] = encoding.WindowsCodePage.ToString();
        //            HTMLEndcoding[2] = encoding.WebName;

        //            foreach (OL.Attachment attachment in mailItem.Attachments)
        //            {
        //                this.eMailAttachments.Add(attachment.FileName);
        //            }

        //            foreach (string attachmentsName in this.eMailAttachments)
        //            {
        //                foreach (OL.Attachment attachment in mailItem.Attachments)
        //                {
        //                    if (attachmentsName == attachment.FileName)
        //                    {
        //                        attachment.SaveAsFile(Path.GetTempPath() + "\\" + attachment.FileName);

        //                        this.notesMIMEEntity.SetContentFromBytes(this.notesStream, "image/jpg", MIME_ENCODING.ENC_IDENTITY_BINARY);
        //                        //notesRichTextItem.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, null, Path.GetTempPath() + "\\" + attachment.FileName, Path.GetTempPath() + "\\" + attachment.FileName);
        //                        File.Delete(Path.GetTempPath() + "\\" + attachment.FileName);
        //                    }
        //                }
        //            }

        //        }
        //    }
        //    return HTMLEndcoding;
        //}

        #endregion HTML support

        private string GetSTMPFromEXAddress(OL.MailItem mailItem)
        {
            string addressEntry = mailItem.SenderEmailAddress;
            string smtpAddress = string.Empty;

            try
            {
                if (addressEntry != null)
                {
                    smtpAddress = this.GetSMTPAddress(addressEntry);
                }
            }
            catch (COMException cx)
            {
                if (cx.ErrorCode != -2147221229)
                {
                    throw new COMException("Fejl i getSTMPFromEXAddress.\n\nSystem besked:\n" + cx.Message + "\n\n"+ cx.StackTrace);
                }
                else
                {
                    //User Cancel
                    //Supress;
                    throw;
                }
            }

            return smtpAddress;
        }

        public string GetSMTPAddress(string exchangeAddress)
        {
            string smtpAddress = string.Empty;
            IAddrBook addrBook = GetAddrBook();
            if (addrBook != null)
                try
                {
                    IntPtr szPtr = IntPtr.Zero;
                    IntPtr propValuePtr = Marshal.AllocHGlobal(16);
                    IntPtr adrListPtr = Marshal.AllocHGlobal(16);

                    Marshal.WriteInt32(propValuePtr, (int)MAPI.PR_DISPLAY_NAME);
                    Marshal.WriteInt32(new IntPtr(propValuePtr.ToInt32() + 4), 0);
                    szPtr = Marshal.StringToHGlobalAnsi(exchangeAddress);
                    Marshal.WriteInt64(new IntPtr(propValuePtr.ToInt32() + 8), szPtr.ToInt32());

                    Marshal.WriteInt32(adrListPtr, 1);
                    Marshal.WriteInt32(new IntPtr(adrListPtr.ToInt32() + 4), 0);
                    Marshal.WriteInt32(new IntPtr(adrListPtr.ToInt32() + 8), 1);
                    Marshal.WriteInt32(new IntPtr(adrListPtr.ToInt32() + 12), propValuePtr.ToInt32());
                    try
                    {
                        if (addrBook.ResolveName(0, MAPI.MAPI_DIALOG, null, adrListPtr) == MAPI.S_OK)
                        {
                            SPropValue spValue = new SPropValue();
                            int pcount = Marshal.ReadInt32(new IntPtr(adrListPtr.ToInt32() + 8));
                            IntPtr props = new IntPtr(Marshal.ReadInt32(new IntPtr(adrListPtr.ToInt32() + 12)));
                            for (int i = 0; i < pcount; i++)
                            {
                                spValue = (SPropValue)Marshal.PtrToStructure(
                                    new IntPtr(props.ToInt32() + (16 * i)), typeof(SPropValue));
                                if (spValue.ulPropTag == MAPI.PR_ENTRYID)
                                {
                                    IntPtr addrEntryPtr = IntPtr.Zero;
                                    IntPtr propAddressPtr = IntPtr.Zero;
                                    uint objType = 0;
                                    uint cb = (uint)(spValue.Value & 0xFFFFFFFF);
                                    IntPtr entryID = new IntPtr((int)(spValue.Value >> 32));
                                    if (addrBook.OpenEntry(cb, entryID, IntPtr.Zero, 0, out objType, out addrEntryPtr) == MAPI.S_OK)
                                        try
                                        {
                                            if (MAPI.HrGetOneProp(addrEntryPtr, MAPI.PR_EMS_AB_PROXY_ADDRESSES, out propAddressPtr) == MAPI.S_OK)
                                            {
                                                IntPtr emails = IntPtr.Zero;
                                                SPropValue addrValue = (SPropValue)Marshal.PtrToStructure(propAddressPtr, typeof(SPropValue));
                                                int acount = (int)(addrValue.Value & 0xFFFFFFFF);
                                                IntPtr pemails = new IntPtr((int)(addrValue.Value >> 32));
                                                for (int j = 0; j < acount; j++)
                                                {
                                                    emails = new IntPtr(Marshal.ReadInt32(new IntPtr(pemails.ToInt32() + (4 * j))));
                                                    smtpAddress = Marshal.PtrToStringAnsi(emails);
                                                    if (smtpAddress.IndexOf("SMTP:") == 0)
                                                    {
                                                        smtpAddress = smtpAddress.Substring(5, smtpAddress.Length - 5);
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                        finally
                                        {
                                            if (propAddressPtr != IntPtr.Zero)
                                                Marshal.Release(propAddressPtr);
                                            if (addrEntryPtr != IntPtr.Zero)
                                                Marshal.Release(addrEntryPtr);
                                        }
                                }
                            }
                        }
                    }
                    finally
                    {
                        Marshal.FreeHGlobal(szPtr);
                        Marshal.FreeHGlobal(propValuePtr);
                        Marshal.FreeHGlobal(adrListPtr);
                    }
                }
                finally
                {
                    Marshal.ReleaseComObject(addrBook);
                }
            return smtpAddress;
        }

        private IAddrBook GetAddrBook()
        {
            if (MAPI.MAPIInitialize(IntPtr.Zero) == MAPI.S_OK)
            {
                IntPtr sessionPtr = IntPtr.Zero;
                MAPI.MAPILogonEx(0, null, null, MAPI.MAPI_EXTENDED | MAPI.MAPI_ALLOW_OTHERS, out sessionPtr);
                if (sessionPtr == IntPtr.Zero)
                    MAPI.MAPILogonEx(0, null, null, MAPI.MAPI_EXTENDED | MAPI.MAPI_NEW_SESSION | MAPI.MAPI_USE_DEFAULT, out sessionPtr);
                if (sessionPtr != IntPtr.Zero)
                    try
                    {
                        object sessionObj = Marshal.GetObjectForIUnknown(sessionPtr);
                        if (sessionObj != null)
                            try
                            {
                                IMAPISession session = sessionObj as IMAPISession;
                                if (session != null)
                                {
                                    IntPtr addrBookPtr = IntPtr.Zero;
                                    session.OpenAddressBook(0, IntPtr.Zero, MAPI.AB_NO_DIALOG, out addrBookPtr);
                                    if (addrBookPtr != IntPtr.Zero)
                                        try
                                        {
                                            object addrBookObj = Marshal.GetObjectForIUnknown(addrBookPtr);
                                            if (addrBookObj != null)
                                                return addrBookObj as IAddrBook;
                                        }
                                        finally
                                        {
                                            Marshal.Release(addrBookPtr);
                                        }
                                }
                            }
                            finally
                            {
                                Marshal.ReleaseComObject(sessionObj);
                            }
                    }
                    finally
                    {
                        Marshal.Release(sessionPtr);
                    }
            }
            else
                throw new ApplicationException("MAPI can not be initialized.");
            return null;
        }

        #region RTF support beta
        [DllImport("mapirtf.dll")]
        private static extern int readrtf(string profileName, string srcMsgID, string srcStoreID, ref string msgRTF);
        #endregion
        #endregion
    }
}